/*
 * MFormatUtil.cpp
 *
 *  Created on: 2017年3月6日
 *      Author: chuanjiang.zh
 */

#include "MFormatUtil.h"
#include "TStringUtil.h"


namespace av
{

static void memClone(const uint8_t* src, size_t size, uint8_t*& dest, int& length)
{
	length = size;
	if (length > 0)
	{
		dest = new uint8_t[length];
		memcpy(dest, src, length);
	}
}


MFormatUtil::MFormatUtil()
{
}

MFormatUtil::~MFormatUtil()
{
}

void MFormatUtil::free(MFormat& fmt)
{
	delete fmt.vProp;
	fmt.vProp = NULL;

	delete fmt.config;
	fmt.config = NULL;

	fmt.vPropSize = 0;
	fmt.configSize = 0;
}

void MFormatUtil::clone(const MFormat& srcFmt, MFormat& fmt)
{
	free(fmt);

	fmt = srcFmt;

	memClone(srcFmt.vProp, srcFmt.vPropSize, fmt.vProp, fmt.vPropSize);

	memClone(srcFmt.config, srcFmt.configSize, fmt.config, fmt.configSize);

}

void MFormatUtil::setVideoProp(MFormat& fmt, const uint8_t* data, size_t length)
{
	free(fmt);

	memClone(data, length, fmt.vProp, fmt.vPropSize);
}

void MFormatUtil::setVideoProp(MFormat& fmt, const std::string& prop)
{
	setVideoProp(fmt, (const uint8_t*)prop.c_str(), prop.size());
}


void MFormatUtil::copyTo(const MFormat* fmt, av::MediaFormat& mfmt)
{
    mfmt.m_codec = fmt->codec;
    mfmt.m_width= fmt->width;
    mfmt.m_height = fmt->height;
    mfmt.m_framerate = fmt->framerate;
    mfmt.m_profile = fmt->profile;
    mfmt.m_clockRate = fmt->clockRate;
	mfmt.m_bitrate = fmt->bitrate;

    mfmt.m_audioCodec = fmt->audioCodec;
    mfmt.m_channels = fmt->channels;
    mfmt.m_sampleRate = fmt->sampleRate;
    mfmt.m_audioProfile = fmt->audioProfile;
    mfmt.m_audioRate = fmt->audioRate;
	mfmt.m_audioBitrate = fmt->audioBitrate;

    if (fmt->vProp && fmt->vPropSize > 0)
    {
        mfmt.m_videoProp.assign((char*)fmt->vProp, fmt->vPropSize);
    }

	if (fmt->config && fmt->configSize > 0)
	{
		mfmt.m_audioConfig.assign((char*)fmt->config, fmt->configSize);
	}
}

void MFormatUtil::copyFrom(MFormat* fmt, const av::MediaFormat& mfmt)
{
    fmt->codec = mfmt.m_codec;
    fmt->width = mfmt.m_width;
    fmt->height = mfmt.m_height;
    fmt->framerate = mfmt.m_framerate;
    fmt->profile = mfmt.m_profile;
    fmt->clockRate = mfmt.m_clockRate;
	fmt->bitrate = mfmt.m_bitrate;

    fmt->audioCodec = mfmt.m_audioCodec;
    fmt->channels = mfmt.m_channels;
    fmt->sampleRate = mfmt.m_sampleRate;
    fmt->audioProfile = mfmt.m_audioProfile;
    fmt->audioRate = mfmt.m_audioRate;
	fmt->audioBitrate = mfmt.m_audioBitrate;

    fmt->vProp = (uint8_t*)mfmt.m_videoProp.c_str();
    fmt->vPropSize = mfmt.m_videoProp.size();

	fmt->config = (uint8_t*)mfmt.m_audioConfig.c_str();
	fmt->configSize = mfmt.m_audioConfig.size();
}

std::string MFormatUtil::toString(const MFormat& fmt)
{
	return comn::StringUtil::format("video:%d,%d,%d, audio:%d,%d,%d",
			fmt.codec, fmt.width, fmt.height,
			fmt.audioCodec, fmt.channels, fmt.sampleRate);
}


} /* namespace av */
